package 寒假刷题;

import java.util.Arrays;
import java.util.Collection;

public class 最少移动次数使数组元素相等2 {
    public int minMoves2(int[] nums) {
        //平均值
//        int avg = Arrays.stream(nums).sum() / nums.length;
//        System.out.println(avg);
//        int res = 0;
//        for (int num : nums) {
//            res += Math.abs(num-res);
//        }
//        return res;
        //中位数
        Arrays.sort(nums);
        int idx = nums.length/2;
        int mid = 0,res = 0 ;
        if (nums.length%2==0){
            mid =  (nums[idx]+nums[idx-1])/2;
        }
        else{
            mid = nums[idx];
        }
        for (int num : nums) {
            res += Math.abs(num-mid);
        }
        return res;
    }
}
